<template>
  <div class="w-full" :style="{ height: `${screenHeight *0.99}px` }">
    <Grid>
      <template #toolbar-actions>
        <Button type="primary" @click="addRowEvent">添加行数据</Button>
      </template>
      <template #action="{ row }">
        <template v-if="hasEditStatus(row)">
          <Button type="link" @click="saveRowEvent(row)">保存</Button>
          <Button type="link" @click="cancelRowEvent(row)">取消</Button>
        </template>
        <template v-else>
          <el-button text type="primary" @click="editRowEvent(row)">编辑</el-button>
          <el-button text type="primary" @click="deleteRowEvent(row)">删除</el-button>
          <el-button text type="primary" @click="handleEdit(row)">订单绑定</el-button>
        </template>
      </template>
    </Grid>
  </div>
</template>

<script lang="ts" setup>
//@ts-ignore
import type { VbenFormProps } from "#/adapter/form";
import { useRouter,useRoute } from "vue-router";
import type { VxeGridProps, VxeGridListeners } from "#/adapter/vxe-table";
import { ElMessage, ElMessageBox, ElUpload, ElDialog,ElButton,ElLoading,ElTag,ElDatePicker} from "element-plus";
import { Button, Upload, RadioButton, RadioGroup } from "ant-design-vue";
import { useVbenVxeGrid } from "#/adapter/vxe-table";
import { $t } from "#/locales";
import { ref, onUnmounted, onMounted,reactive, nextTick } from "vue";
import { useVbenModal, VbenButton } from "@vben/common-ui";
import { dealVxeGridFilterParameter,getRandom } from "#/utils/tools.ts";
//@ts-ignore
import {  reqQualityTestingList,reqUpdateQualityTesting,reqSaveQualityTesting,reqDelQualityTestingBatch } from "#/api/qualityTesting/index.ts";
const router = useRouter(), route = useRoute();


const screenHeight = ref<number>(window.innerHeight);

function handleResize(): void {
  screenHeight.value = window.innerHeight;
  console.log("Screen height after resize:", screenHeight.value);
}
onMounted(() => {
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
  return () => {
    window.removeEventListener("resize", handleResize);
  };
});

const filterParams = ref(null);

const formOptions: VbenFormProps = {
  collapsed: true,
  schema: [
    {
      component: "DatePicker",
      fieldName: "dateList",
      label: "创建时间段",
      componentProps: {
        type: "datetimerange",
        startPlaceholder: "开始时间",
        endPlaceholder: "结束时间",
        format: "YYYY-MM-DD HH:mm:ss",
        valueFormat: "YYYY-MM-DD HH:mm:ss"
      }
    }
  ],
  showCollapseButton: true,
  submitButtonOptions: { content: "查询" }
};
const gridOptions: VxeGridProps = ref({
  columns: [
    { title: "序号", type: "seq", width: 50 },
    { field:"productNumber", title:"生产订单号", width:"180",editRender: { name: 'ElInput' } },
    { field: "eui", title: "设备编码", width: "",editRender: { name: 'ElInput' } },
    { field:"deviceName", title:"设备名称", width:"",editRender: { name: 'ElInput' } },
    { field:"createTime", title:"创建时间", width:"200",editRender: { name: 'ElDatePicker' } },
    { fixed: "right", slots: { default: "action" }, title: "操作", width: 250, visible: true }
  ],
  toolbarConfig: {
    search: false,
    custom: true,
    export: false,
    refresh: true,
    zoom: true
  },
  filterConfig: {
    remote: true
  },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    pageSize: 20,
    pageSizes: [10, 20, 30, 50, 100]
  },
  height: "100%",
  autoResize:true,
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true,
    autoClear: false
  },
  editRules: {
    productNumber: [
      { required: true, message: '请输入产品订单号' },
      { validator({ cellValue }){if(!cellValue){ return new Error('请输入产品订单号');}} }
    ]
  },
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query: ({ page }, formValues) => proxyConfigQueryEvent({ page, formValues })
    }
  }
});

const gridEvents = {
  filterChange({ filterList }){
    filterParams.value = dealVxeGridFilterParameter(filterList);
    gridApi.query();
  }
}

const proxyConfigQueryEvent = async (option:any) => {
  const { page,formValues } = option;
  const params:any = { page:page.currentPage,size:page.pageSize };
  const { dateList } = formValues;
  if(dateList && dateList.length === 2){
    params.startTime = dateList[0];
    params.endTime = dateList[1];
  }
  if(filterParams.value){
    Object.assign(params,filterParams.value);
  }
  try {
    const response = await reqQualityTestingList(params);
    return {
      total: response.data.totalElements,
      items: dealResponseData(response.data.content)
    };
  } catch {
    return { items: [], total: 0 };
  }
}

const dealResponseData = (list:any[]) => {
  const array = [];
  const dynamicColumnNames = [];
  for(let i = 0; i < list.length; i++){
    const { id,eui,deviceName,createTime,iotDeviceInspectDetailList } = list[i];
    const obj = { id,eui,deviceName,createTime };
    iotDeviceInspectDetailList.forEach(item => {
      obj[item.name] = item.value;
      if(i == 0 ) dynamicColumnNames.push({ field:item.name,title:item.title });
    })
    array.push(obj);
  }
  generateDynamicColumns(dynamicColumnNames);
  return array;
}


const generateDynamicColumns = (dynamicColumnNames: any[]) => {
  const list = [];
  for(let i = 0; i < dynamicColumnNames.length; i++){
    const { field,title } = dynamicColumnNames[i];
    const formatter = ({ cellValue,row,column }) => { return cellValue };
    const editRender = { name: 'ElInput' };
    list.push({ field,title,width:150,formatter,editRender });
  }
  const columns = gridApi.grid.columns;
  const resultColumns = [].concat(columns.slice(0,columns.length - 2),list,columns.slice(columns.length - 2,columns.length));
  gridApi.grid.loadColumn(resultColumns);
}



const [Grid, gridApi] = useVbenVxeGrid({ formOptions,gridOptions,gridEvents });


const handleEdit = (row:any) => {
  router.push({ path: "/qualityTesting/coProductOrder",query:{ dateTime:row.createTime }});
}

const addRowEvent = async () => {
  const grid = gridApi.grid;
  const obj = { randomId:getRandom() };
  const newRow = await grid.createRow(obj);
  await grid.insertAt(newRow, 0);
  await nextTick();
  grid.setEditRow(newRow);
}

const hasEditStatus = (row: any) => {
  const grid = gridApi.grid;
  if (grid) {
    return grid.isEditByRow(row);
  }
}

const deleteRowEvent = (row:any) => {
  ElMessageBox.confirm("确定删除当前行数据吗", {confirmButtonText: "确定",cancelButtonText: "取消",type: "warning"}).then(() => {
    //
  })
}
const saveRowEvent = (row: any) => {
  const { id,productNumber,randomId } = row;
  const parameter = {
    id: row.id,
    productNumber: row.productNumber
  };
  if(randomId){
    //新增行数据
  } else {
    //修改行数据
  }
  ElMessageBox.confirm("确定保存当前行数据吗", {confirmButtonText: "确定",cancelButtonText: "取消",type: "warning"}).then(() => {
    //
  })
};
const cancelRowEvent = (row:any) => {
  const grid = gridApi.grid;
  if (grid) {
    grid.clearEdit().then(() => {
      grid.revertData(row);
    })
  }
}
const editRowEvent = (row:any) => {
  const grid = gridApi.grid;
  if (grid) {
    grid.setEditRow(row);
  }
}
</script>


<style lang="sass" scoped></style>